package com.robert.maps;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.andnav.osm.OpenStreetMapActivity;
import org.andnav.osm.util.GeoPoint;
import org.andnav.osm.util.TypeConverter;
import org.andnav.osm.util.constants.OpenStreetMapConstants;
import org.andnav.osm.views.OpenStreetMapView;
import org.andnav.osm.views.controller.OpenStreetMapViewController;
import org.andnav.osm.views.overlay.OpenStreetMapViewItemizedOverlay;
import org.andnav.osm.views.overlay.OpenStreetMapViewItemizedOverlayWithFocus;
import org.andnav.osm.views.overlay.OpenStreetMapViewOverlayItem;
import org.andnav.osm.views.overlay.OpenStreetMapViewSimpleLocationOverlay;
import org.andnav.osm.views.util.OpenStreetMapRendererInfo;
import org.andnav.osm.views.util.StreamUtils;
import org.andnav.osm.views.util.Util;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.SearchManager;
import android.provider.SearchRecentSuggestions;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.view.Display;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;
//joeng POI
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.robert.maps.utils.Ut;
import com.robert.maps.SearchResultOverlay;
import com.robert.maps.utils.SearchSuggestionsProvider;

public class MainView extends OpenStreetMapActivity implements OpenStreetMapConstants {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	private OpenStreetMapView mOsmv; //, mOsmvMinimap;
	private OpenStreetMapViewSimpleLocationOverlay mMyLocationOverlay;
	private SearchResultOverlay mSearchResultOverlay;
	//joeng POI
	private SQLiteDatabase mPOI;

	private PowerManager.WakeLock myWakeLock;
	private boolean mFullScreen;
	private boolean mShowTitle;
	private String mStatusListener = "";
	private boolean mAutoFollow = true;
	private Handler mCallbackHandler = new MainActivityCallbackHandler();
	private ImageView ivAutoFollow;
	private CompassView mCompassView;
	private SensorManager mOrientationSensorManager;
	private SensorManager mPOSSensorManager;
	private boolean mRotateMapEnabled = false;
	private boolean mCompassEnabled;
	private boolean mDrivingDirectionUp;
	private boolean mNorthDirectionUp;
	private float mLastSpeed;
	//joeng
	private OpenStreetMapViewItemizedOverlayWithFocus<OpenStreetMapViewOverlayItem> mMyPOIOverlay;
	private ArrayList<OpenStreetMapViewOverlayItem> items = new ArrayList<OpenStreetMapViewOverlayItem>();
	
	//joeng change to Class Lvl variable to allow been called by internal method
	private ImageView ivZoomOut;
    private ImageView ivZoomIn;
    private float bearingAngle=0;
    private boolean rotateMap=false;

    private final SensorEventListener mPOSListener = new SensorEventListener() {
    	public void onSensorChanged(SensorEvent event) {
	    	if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
				if (Math.abs(event.values[0]) >0.7 )
					rotateMap=true;
				else
					rotateMap=false;
			}
    	}

		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			// TODO Auto-generated method stub
			
		}
    };
    
	private final SensorEventListener mListener = new SensorEventListener() {

		private int iOrientation = -1;
		
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			// Auto-generated method stub

		}

		public void onSensorChanged(SensorEvent event) {
			if (event.sensor.getType() == Sensor.TYPE_ORIENTATION){
				if (iOrientation < 0)
					iOrientation = ((WindowManager) MainView.this.getSystemService(Context.WINDOW_SERVICE))
								.getDefaultDisplay().getOrientation();
						
				mCompassView.setAzimuth(event.values[0] + 90 * iOrientation);
				//mCompassView.setAzimuth(event.values[0]);
				mCompassView.invalidate();

				//if (mCompassEnabled){
				if (mRotateMapEnabled){
					if (mNorthDirectionUp)
						//if (mDrivingDirectionUp == false || mLastSpeed == 0) {
						if (mDrivingDirectionUp == false || mLastSpeed <3 ) {
							//if (Math.abs(event.values[0]-bearingAngle)>5){
							//quick rotate || slow rotate & degree change > 5
							if ((rotateMap || mOsmv.getBearing() == 0) || 
									(!rotateMap && Math.abs(event.values[0]-bearingAngle)>5)){
								bearingAngle=event.values[0];
								mOsmv.setBearing(event.values[0] + 90 * iOrientation);
								mOsmv.invalidate();
							}
						}
				}
			}
		}

	};

	// ===========================================================
	// Constructors
	// ===========================================================

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, false); // Pass true here to actually contribute to OSM!

		mOrientationSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
		mPOSSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
		
       	final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);

 		final RelativeLayout rl = new RelativeLayout(this);
        OpenStreetMapRendererInfo RendererInfo = getRendererInfo(getResources(), getPreferences(Activity.MODE_PRIVATE), "mapnik");
        this.mOsmv = new OpenStreetMapView(this, RendererInfo);
        this.mOsmv.setMainActivityCallbackHandler(mCallbackHandler);
        rl.addView(this.mOsmv, new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

        //joeng POI
    	if (mPOI == null)
		{
			this.mPOI= Util.getPOIDatabase(false);
			this.mPOI.execSQL("CREATE TABLE IF NOT EXISTS PlacesInfo (PlaceID INTEGER PRIMARY KEY AUTOINCREMENT, name NVARCHAR(100), " +
					"description NVARCHAR(1024), category NVARCHAR(100), city NVARCHAR(100), show boolean);");
					//actual key is "PRIMARY KEY(name,category,city) );");, id is for foreign key.
			this.mPOI.execSQL("CREATE TABLE IF NOT EXISTS PlacesGeoPoint (PlaceID INTEGER, latitude INTEGER NOT NULL, longitude INTEGER NOT NULL);");
			this.mPOI.execSQL("CREATE TABLE IF NOT EXISTS Category (name NVARCHAR(100), description NVARCHAR(1024), " +
					"ID INTEGER NOT NULL, PRIMARY KEY(ID) );");
		}

        /* SingleLocation-Overlay */
        {
	        /* Create a static Overlay showing a single location. (Gets updated in onLocationChanged(Location loc)! */
        	if(RendererInfo.YANDEX_TRAFFIC_ON == 1)
        		this.mOsmv.getOverlays().add(new YandexTrafficOverlay(this, this.mOsmv));

	        this.mMyLocationOverlay = new OpenStreetMapViewSimpleLocationOverlay(this);
	        this.mOsmv.getOverlays().add(mMyLocationOverlay);
	        
	        this.mSearchResultOverlay = new SearchResultOverlay(this);
	        this.mOsmv.getOverlays().add(mSearchResultOverlay);
        }

        {
        	final boolean sideBottom = pref.getBoolean("pref_bottomzoomcontrol", false);

            /* Compass */
        	mCompassView = new CompassView(this, sideBottom);
	        mCompassView.setVisibility(mCompassEnabled ? View.VISIBLE : View.INVISIBLE);
	        /* Create RelativeLayoutParams, that position in in the top right corner. */
	        final RelativeLayout.LayoutParams compassParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
	        compassParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
	        compassParams.addRule(!sideBottom ? RelativeLayout.ALIGN_PARENT_BOTTOM : RelativeLayout.ALIGN_PARENT_TOP);
	        rl.addView(mCompassView, compassParams);

            /* AutoFollow */
	        ivAutoFollow = new ImageView(this);
	        ivAutoFollow.setImageResource(R.drawable.autofollow);
	        ivAutoFollow.setVisibility(ImageView.INVISIBLE);
	        /* Create RelativeLayoutParams, that position in in the top right corner. */
	        final RelativeLayout.LayoutParams followParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
	        followParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
	        followParams.addRule(!sideBottom ? RelativeLayout.ALIGN_PARENT_BOTTOM : RelativeLayout.ALIGN_PARENT_TOP);
	        rl.addView(ivAutoFollow, followParams);

	        ivAutoFollow.setOnClickListener(new OnClickListener(){
				// @Override
				public void onClick(View v) {
					setAutoFollow(true);
					mSearchResultOverlay.Clear();
					setLastKnownLocation();
				}
	        });

	        /* ZoomControls */
	        /* Create a ImageView with a zoomIn-Icon. */
	        //joeng change to Class Lvl variable to allow been called by internal method
	        //final ImageView ivZoomIn = new ImageView(this);
	        ivZoomIn = new ImageView(this);
	        ivZoomIn.setImageResource(R.drawable.zoom_in);
	        /* Create RelativeLayoutParams, that position in in the top right corner. */
	        final RelativeLayout.LayoutParams zoominParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
	        zoominParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
	        zoominParams.addRule(sideBottom ? RelativeLayout.ALIGN_PARENT_BOTTOM : RelativeLayout.ALIGN_PARENT_TOP);
	        rl.addView(ivZoomIn, zoominParams);

	        ivZoomIn.setOnClickListener(new OnClickListener(){
				// @Override
				public void onClick(View v) {
					MainView.this.mOsmv.zoomIn();
					setTitle();

					if(MainView.this.mOsmv.getZoomLevel() > 16 && MainView.this.mOsmv.getRenderer().YANDEX_TRAFFIC_ON == 1)
						Toast.makeText(MainView.this, R.string.no_traffic, Toast.LENGTH_SHORT).show();
				}
	        });
	        ivZoomIn.setOnLongClickListener(new OnLongClickListener(){
				// @Override
				public boolean onLongClick(View v) {
					SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainView.this);
					final int zoom = Integer.parseInt(pref.getString("pref_zoommaxlevel", "0"));
					if (zoom > 0) {
						MainView.this.mOsmv.setZoomLevel(zoom - 1);
						setTitle();
					}
					return true;
				}
	        });


	        /* Create a ImageView with a zoomOut-Icon. */
	        //joeng change to Class Lvl variable to allow been called by internal method
	        //final ImageView ivZoomOut = new ImageView(this);
	        ivZoomOut = new ImageView(this);
	        ivZoomOut.setImageResource(R.drawable.zoom_out);

	        /* Create RelativeLayoutParams, that position in in the top left corner. */
	        final RelativeLayout.LayoutParams zoomoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
	        zoomoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
	        zoomoutParams.addRule(sideBottom ? RelativeLayout.ALIGN_PARENT_BOTTOM : RelativeLayout.ALIGN_PARENT_TOP);
	        rl.addView(ivZoomOut, zoomoutParams);

	        ivZoomOut.setOnClickListener(new OnClickListener(){
				// @Override
				public void onClick(View v) {
					MainView.this.mOsmv.zoomOut();
					setTitle();
				}
	        });
	        ivZoomOut.setOnLongClickListener(new OnLongClickListener(){
				// @Override
				public boolean onLongClick(View v) {
					SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainView.this);
					final int zoom = Integer.parseInt(pref.getString("pref_zoomminlevel", "0"));
					if (zoom > 0) {
						MainView.this.mOsmv.setZoomLevel(zoom - 1);
						setTitle();
					}
					return true;
				}
	        });
        }


		mDrivingDirectionUp = pref.getBoolean("pref_drivingdirectionup", true);
		mNorthDirectionUp = pref.getBoolean("pref_northdirectionup", true);

     	mFullScreen = pref.getBoolean("pref_showstatusbar", true);
		if (mFullScreen)
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		else
			getWindow()
					.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

		mShowTitle = pref.getBoolean("pref_showtitle", true);
		if (mShowTitle)
	        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		else
			requestWindowFeature(Window.FEATURE_NO_TITLE);

        this.setContentView(rl);

        if(mShowTitle)
	        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.main_title);

		restoreUIState();

        final Intent queryIntent = getIntent();
        final String queryAction = queryIntent.getAction();

        if (Intent.ACTION_SEARCH.equals(queryAction)) {
            doSearchQuery(queryIntent);
        }

    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_option_menu, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		switch (item.getItemId()) {
		//joeng POI
		case (R.id.poi):
			return true;
		case (R.id.ic_submenu_managepoi):			
			//Intent intent = new Intent();
			//intent.setClass(this, POIList.class);
			//startActivityForResult(intent, 12345);
			
			startActivityForResult(new Intent(this, POIList.class),20000);
			//startActivityForResult(new Intent(this, POIExpList.class),20000);
			return true;
		case (R.id.ic_submenu_markloc):
			markLocAsPOI();
			return true;
		case (R.id.settings):
			startActivityForResult(new Intent(this, MainPreferences.class), 12345);
			return true;
		case (R.id.about):
			showDialog(R.id.about);
			return true;
		case (R.id.mapselector):
			return true;
		case (R.id.compass):
			Menu submenu = item.getSubMenu();
			if (mCompassEnabled){
				submenu.findItem(R.id.ic_submenu_showcompass).setTitle("Hide Compass");
			}
			else
				submenu.findItem(R.id.ic_submenu_showcompass).setTitle("Show Compass");

			if (mRotateMapEnabled){
				submenu.findItem(R.id.ic_submenu_rotatemap).setTitle("Stop Rotate Map");
			}
			else
				submenu.findItem(R.id.ic_submenu_rotatemap).setTitle("Rotate Map");

			return true;
		case (R.id.ic_submenu_showcompass):
			if (item.getTitle()=="Show Compass")
				setCompassMode(mRotateMapEnabled,true);
			else
				setCompassMode(mRotateMapEnabled,false);
			return true;
		case (R.id.ic_submenu_rotatemap):
			if (item.getTitle()=="Rotate Map")
				setCompassMode(true,mCompassEnabled);
			else
				setCompassMode(false,mCompassEnabled);
			return true;
		case (R.id.mylocation):
			setAutoFollow(true);
			setLastKnownLocation();
			return true;
		default:
 			OpenStreetMapRendererInfo RendererInfo = getRendererInfo(getResources(), getPreferences(Activity.MODE_PRIVATE), (String)item.getTitleCondensed());
			mOsmv.setRenderer(RendererInfo);

			this.mOsmv.getOverlays().clear();
			showPOILayer(items,false);
        	this.unSetPOIitems();
        	
			if(RendererInfo.YANDEX_TRAFFIC_ON == 1){
	       		this.mOsmv.getOverlays().add(new YandexTrafficOverlay(this, this.mOsmv));
			}
	        this.mOsmv.getOverlays().add(mMyLocationOverlay);
	        this.mOsmv.getOverlays().add(mSearchResultOverlay);
	        setTitle();
			return true;
		}

	}

	/**
	 * 
	 */
	private void markLocAsPOI() {
		final Location loc = getLastKnowLocation(40001);
		if (loc != null){
			final GeoPoint tmpPoint = TypeConverter.locationToGeoPoint(loc);
			showEditPOIDialog(MainView.this, tmpPoint.getLatitudeE6() , tmpPoint.getLongitudeE6());
		}
	}

	private void setCompassMode(boolean rotateMap, boolean showCompass) {
		mRotateMapEnabled = rotateMap;
		//mCompassEnabled = !mCompassEnabled;
		mCompassEnabled = showCompass;
		mCompassView.setVisibility(mCompassEnabled ? View.VISIBLE : View.INVISIBLE);
			//if(mCompassEnabled){
		if (!mCompassEnabled && !mRotateMapEnabled){
			mOrientationSensorManager.unregisterListener(mListener);
		}
		else{
			mOrientationSensorManager.registerListener(mListener, 
					mOrientationSensorManager.
					getDefaultSensor(Sensor.TYPE_ORIENTATION), 
					SensorManager.SENSOR_DELAY_UI);
		}
						
		if(mRotateMapEnabled){
			mPOSSensorManager.registerListener(mPOSListener, 
					mPOSSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 
					SensorManager.SENSOR_DELAY_UI);
		}
		else{
			mPOSSensorManager.unregisterListener(mPOSListener);
			if (mOsmv.getBearing() != 0){
				mOsmv.setBearing(0);
				mOsmv.invalidate();
			}				
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case R.id.whatsnew:
			return new AlertDialog.Builder(this) //.setIcon( R.drawable.alert_dialog_icon)
					.setTitle(R.string.about_dialog_whats_new)
					.setMessage(R.string.whats_new_dialog_text)
					.setNegativeButton(R.string.about_dialog_close, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {

							/* User clicked Cancel so do some stuff */
						}
					}).create();
		case R.id.about:
			return new AlertDialog.Builder(this) //.setIcon(R.drawable.alert_dialog_icon)
					.setTitle(R.string.menu_about)
					.setMessage(getText(R.string.app_name) + " v." + Ut.getAppVersion(this) + "\n\n"
							+ getText(R.string.about_dialog_text))
					.setPositiveButton(R.string.about_dialog_whats_new, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {

							showDialog(R.id.whatsnew);
						}
					}).setNegativeButton(R.string.about_dialog_close, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {

							/* User clicked Cancel so do some stuff */
						}
					}).create();
		}
		return null;
	}

	private void setLastKnownLocation() {
		Location loc = getLastKnowLocation(40000);
		if (loc != null)
			this.mOsmv
					.getController()
					.animateTo(
							TypeConverter.locationToGeoPoint(loc),
							OpenStreetMapViewController.AnimationType.MIDDLEPEAKSPEED,
							OpenStreetMapViewController.ANIMATION_SMOOTHNESS_HIGH,
							OpenStreetMapViewController.ANIMATION_DURATION_DEFAULT);
	}

	/**
	 * @return
	 */
	private Location getLastKnowLocation(int CallerId) {
		final LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		final Location loc1 = lm.getLastKnownLocation("gps");
		final Location loc2 = lm.getLastKnownLocation("network");
		Location loc = null;
		//joeng
		if (!lm.isProviderEnabled("gps") && !lm.isProviderEnabled("network")){
			Toast.makeText(this, "No location provider available now! Please enable related System Setting.", 8000).show();
			startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), CallerId);
		}
		else
		{
			if (loc1 == null && loc2 == null)
				Toast.makeText(this, "Can not get Location now!", 8000).show();
			else if(loc1 == null && loc2 != null)
				loc = loc2;
			else if (loc1 != null && loc2 == null)
				loc = loc1;
			else
				loc = loc1.getTime() > loc2.getTime() ? loc1 : loc2;
		}
		return loc;
	}

	private void setAutoFollow(boolean autoFollow) {
		if (mAutoFollow != autoFollow) {
			mAutoFollow = autoFollow;

			if (autoFollow) {
				ivAutoFollow.setVisibility(ImageView.INVISIBLE);
				//Toast.makeText(this, R.string.auto_follow_enabled, Toast.LENGTH_SHORT).show();
			} else {
				ivAutoFollow.setVisibility(ImageView.VISIBLE);
				//Toast.makeText(this, R.string.auto_follow_disabled, Toast.LENGTH_SHORT).show();
			}
		}
	}

	//joeng method to set visibility of Zoom In/Out button
	private void setMaxMinZoom(boolean showMaxZoom,boolean showMinZoom) {
		
		if (showMaxZoom)
			this.ivZoomIn.setVisibility(ImageView.VISIBLE);
		else
			this.ivZoomIn.setVisibility(ImageView.INVISIBLE);

		if (showMinZoom)
			this.ivZoomOut.setVisibility(ImageView.VISIBLE);
		else
			this.ivZoomOut.setVisibility(ImageView.INVISIBLE);
	}
	
	@Override
	public void onLocationChanged(Location loc) {
		this.mMyLocationOverlay.setLocation(loc);

		mLastSpeed = loc.getSpeed();

		if (mAutoFollow) {
			if (mDrivingDirectionUp)
				//if (mLastSpeed > 0)
				if (mLastSpeed >= 3)
					this.mOsmv.setBearing(loc.getBearing());

			this.mOsmv.getController().animateTo(TypeConverter.locationToGeoPoint(loc), OpenStreetMapViewController.AnimationType.MIDDLEPEAKSPEED, OpenStreetMapViewController.ANIMATION_SMOOTHNESS_HIGH, OpenStreetMapViewController.ANIMATION_DURATION_DEFAULT);
		}
		else
			this.mOsmv.invalidate();
	}

	@Override
	public void onLocationLost() {
		// Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		int cnt = extras.getInt("satellites", Integer.MIN_VALUE);
		mStatusListener = provider+ " " + status + " " + (cnt >= 0 ? cnt : 0);
		setTitle();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		Menu submenu = menu.findItem(R.id.mapselector).getSubMenu();
		submenu.clear();
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);

		File folder = Util.getRMapsFolder("maps", true);
		if (folder.exists()) {
			File[] files = folder.listFiles();
			if (files != null)
				for (int i = 0; i < files.length; i++) {
					if (files[i].getName().toLowerCase().endsWith(".mnm")
							|| files[i].getName().toLowerCase().endsWith(".tar")
							//joeng add support of SQLiteDB source
							|| files[i].getName().toLowerCase().endsWith(".sdb")) {
						String name = Util.FileName2ID(files[i].getName());
						if (pref.getBoolean("pref_usermaps_" + name + "_enabled", false)) {
							MenuItem item = submenu.add(pref.getString("pref_usermaps_" + name + "_name", files[i]
									.getName()));
							item.setTitleCondensed("usermap_" + name);
						}
					}
				}
		}
		InputStream in = getResources().openRawResource(R.raw.predefmaps);
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = null;
		try {
			db = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e1) {
			e1.printStackTrace();
		}
		Document doc = null;
		try {
			doc = db.parse(in);

			NodeList nl = doc.getDocumentElement().getElementsByTagName("map");
			for(int i = 0; i < nl.getLength(); i++){
				NamedNodeMap nnm =nl.item(i).getAttributes();

				Node nodeLayer = nnm.getNamedItem("layer");
				boolean ItIsLayer = false;
				if(nodeLayer != null)
					ItIsLayer = nodeLayer.getNodeValue().equalsIgnoreCase("true");

				if(pref.getBoolean("pref_predefmaps_"+nnm.getNamedItem("id").getNodeValue(), true) && !ItIsLayer){
					MenuItem item = submenu.add(nnm.getNamedItem("name").getNodeValue());
					item.setTitleCondensed(nnm.getNamedItem("id").getNodeValue());
					Log.e(DEBUGTAG, nnm.getNamedItem("name").getNodeValue());
				}
			}
		} catch (SAXException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	protected void onPause() {
		SharedPreferences uiState = getPreferences(0);
		SharedPreferences.Editor editor = uiState.edit();
		editor.putString("MapName", mOsmv.getRenderer().ID);
		editor.putInt("Latitude", mOsmv.getMapCenterLatitudeE6());
		editor.putInt("Longitude", mOsmv.getMapCenterLongitudeE6());
		editor.putInt("ZoomLevel", mOsmv.getZoomLevel());
		editor.putBoolean("CompassEnabled", mCompassEnabled);
		editor.putBoolean("RotateMapEnabled", mRotateMapEnabled);
		editor.putString("app_version", Ut.getAppVersion(this));
		mSearchResultOverlay.toPref(editor);
		editor.commit();

		if (myWakeLock != null) {
			myWakeLock.release();
		}

		mOrientationSensorManager.unregisterListener(mListener);
		mPOSSensorManager.unregisterListener(mPOSListener);

		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();

    	SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);

		if (pref.getBoolean("pref_keepscreenon", true)) {
			myWakeLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(
					PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "RMaps");
			myWakeLock.acquire();
		} else {
			myWakeLock = null;
		}

		if(mCompassEnabled){
			mOrientationSensorManager.registerListener(mListener, mOrientationSensorManager
				.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_UI);
		}
		if(mRotateMapEnabled){
			mPOSSensorManager.registerListener(mPOSListener, mPOSSensorManager
				.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
		}
	}

	private OpenStreetMapRendererInfo getRendererInfo(final Resources aRes, final SharedPreferences aPref, final String aName){
		OpenStreetMapRendererInfo RendererInfo = new OpenStreetMapRendererInfo(aRes, aName);
		RendererInfo.LoadFromResources(aName, PreferenceManager.getDefaultSharedPreferences(this));


		return RendererInfo;
	}

	private void restoreUIState() {
		SharedPreferences settings = getPreferences(Activity.MODE_PRIVATE);

		OpenStreetMapRendererInfo RendererInfo = getRendererInfo(getResources(), settings, settings.getString("MapName", "mapnik"));
		if(!mOsmv.setRenderer(RendererInfo))
			mOsmv.setRenderer(getRendererInfo(getResources(), settings, "mapnik"));

		this.mOsmv.getOverlays().clear();
		/*joeng POI Itemized Overlay */
	        {
        		/* Create a static ItemizedOverlay showing a some Markers on some cities. */
	        	showPOILayer(items,false);
	        	this.unSetPOIitems();
        	}
		
		if(RendererInfo.YANDEX_TRAFFIC_ON == 1){
       		this.mOsmv.getOverlays().add(new YandexTrafficOverlay(this, this.mOsmv));
		}
        this.mOsmv.getOverlays().add(mMyLocationOverlay);
        this.mOsmv.getOverlays().add(mSearchResultOverlay);
        
		mOsmv.setZoomLevel(settings.getInt("ZoomLevel", 0));
		mOsmv.setMapCenter(settings.getInt("Latitude", 0), settings.getInt("Longitude", 0));

		mCompassEnabled = settings.getBoolean("CompassEnabled", false);
		mRotateMapEnabled = settings.getBoolean("RotateMapEnabled", false);
		mCompassView.setVisibility(mCompassEnabled ? View.VISIBLE : View.INVISIBLE);

		setTitle();
		mSearchResultOverlay.fromPref(settings);
		
		if(!settings.getString("app_version", "").equalsIgnoreCase(Ut.getAppVersion(this)))
			showDialog(R.id.whatsnew);
	}

	//joeng POI
	private void showPOILayer(ArrayList<OpenStreetMapViewOverlayItem> items, boolean refreshView) {
		showPOILayer(items,null,null,null,0,0,refreshView,null,null);
	}
	
	private void showPOILayer(ArrayList<OpenStreetMapViewOverlayItem> items,String ID, String aName, String aDescription,
			int aLatitude, int aLongitude, boolean refreshView, String aCategory, String aCity) {
		try{
			boolean hasPOI = false;
			boolean newPOI = false;
			ArrayList<Integer> aPathPosList = new ArrayList<Integer>();
			
			/* Create a static ItemizedOverlay showing a some Markers on some cities. */
			if (aName == null){ //get from Database
				String POIID = "", POIName = "", POIDescription = "",POICategory = "", POICity = "";
				ArrayList aGeoPointList;
				final Cursor c = this.mPOI.rawQuery("SELECT a.PlaceID, a.name, a.description,b.latitude,b.longitude,a.category, a.city " +
						" FROM PlacesInfo a inner join PlacesGeoPoint b on a.PlaceID = b.PlaceID where a.show = 1", null);
				if (c.moveToFirst()) {
					items.clear();
					aGeoPointList = new ArrayList<GeoPoint>();
					POIID = c.getString(0);
					do {
						//id, name, description, latitude, longitude, category,city
						if (!POIID.equalsIgnoreCase(c.getString(0))){
							items.add(new OpenStreetMapViewOverlayItem(POIID, POIName, POIDescription, 
									aGeoPointList,POICategory,POICity));
							POIID = c.getString(0);
							if (aGeoPointList.size() > 1)
								aPathPosList.add(items.size()-1);
							aGeoPointList.clear();
						}
						POIName = c.getString(1);
						POIDescription = c.getString(2);
						POICategory = c.getString(5);
						POICity = c.getString(6);
						aGeoPointList.add(new GeoPoint(c.getInt(3), c.getInt(4)));
					} while (c.moveToNext());
					// add the final one to items
					items.add(new OpenStreetMapViewOverlayItem(POIID, POIName, POIDescription, 
							aGeoPointList,POICategory,POICity));
					if (aGeoPointList.size() > 1)
						aPathPosList.add(items.size()-1);
					aGeoPointList.clear();
					aGeoPointList = null;
					
					hasPOI=true;
				}
				c.close();
			}
			else{ //new POI added
				items.add(new OpenStreetMapViewOverlayItem(ID, aName, aDescription, new GeoPoint(aLatitude, aLongitude),
						aCategory, aCity));
				hasPOI=true;
				newPOI=true;
			}
				
			if (hasPOI){
			    /* OnTapListener for the Markers, shows a simpel Toast. */
				if (this.mMyPOIOverlay == null){
				    this.mMyPOIOverlay = new OpenStreetMapViewItemizedOverlayWithFocus<OpenStreetMapViewOverlayItem>(this, items, 
				    new OpenStreetMapViewItemizedOverlay.OnItemTapListener<OpenStreetMapViewOverlayItem>(){
				    	//@Override
						public boolean onItemTap(int index, OpenStreetMapViewOverlayItem item) {
	//						Toast.makeText(MainView.this, "Item '" + item.mTitle + "' (index=" + index + ") got tapped", Toast.LENGTH_LONG).show();
							return true; // We 'handled' this event.
						}
				    },
				    new OpenStreetMapViewItemizedOverlay.OnItemLongPressListener<OpenStreetMapViewOverlayItem>(){
				    	//@Override
						public boolean onItemLongPress(int index, OpenStreetMapViewOverlayItem item) {
							//Toast.makeText(MainView.this, "Item '" + item.mTitle + "' (index=" + index + ") got longpress", Toast.LENGTH_LONG).show();
							showEditPOIDialog(MainView.this,item.mPlaceID, item.mTitle,item.mDescription,item.mCategory,item.mCity,
									item.mGeoPointList.get(0).getLatitudeE6(),item.mGeoPointList.get(0).getLongitudeE6(), false);
							return true; // We 'handled' this event.
						}
				    }			    
				    );				
				}
	
			    this.mMyPOIOverlay.setFocusItemsOnTap(true);
			    this.mMyPOIOverlay.setPathPosList(aPathPosList);
			    if (newPOI) {this.mMyPOIOverlay.setFocusedItem(items.size()-1);}
			    if (!this.mOsmv.getOverlays().contains(mMyPOIOverlay))
			    	this.mOsmv.getOverlays().add(mMyPOIOverlay);
			    if (refreshView)
			    	this.mOsmv.invalidate();
			}
			else if (this.mOsmv.getOverlays().contains(mMyPOIOverlay))
		    	this.mOsmv.getOverlays().remove(mMyPOIOverlay);
		}catch (Exception e){
			Toast.makeText(this, e.toString(), Toast.LENGTH_LONG);
		}
	}
	//joeng POI end
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//joeng user choose go to the POI he/she selected in POI list
		//joeng return from preference or POIList
		if(requestCode == 12345 ){
			finish();
			startActivity(new Intent(this, this.getClass()));
		}
		else if (requestCode == 40000){ // setLastKnowLocation
			final LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			if (lm.isProviderEnabled("gps") || lm.isProviderEnabled("network"))
				setLastKnownLocation();
		}
		else if (requestCode == 40001){ // mark current location as POI
			// do nothing, since the loc get just after loc provider enable is not accuracy 
//			final LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//			if (lm.isProviderEnabled("gps") || lm.isProviderEnabled("network"))
//				markLocAsPOI();
			
		}
		else if ((requestCode == 20000 && resultCode != 20003)){
			this.unSetPOIitems();
			showPOILayer(items,true);
		}
		else if(resultCode == 20003){ 
			if (!data.getAction().equalsIgnoreCase("0")){
				this.unSetPOIitems();
				String[] sGeoPoint= data.getAction().split(",");
				setAutoFollow(false); 
				this.mOsmv.setZoomLevel(16);
				this.mOsmv.getController().animateTo(new GeoPoint(
						Integer.parseInt(sGeoPoint[0]), 
						Integer.parseInt(sGeoPoint[1])), 
						OpenStreetMapViewController.AnimationType.MIDDLEPEAKSPEED, 
						OpenStreetMapViewController.ANIMATION_SMOOTHNESS_HIGH, 
						OpenStreetMapViewController.ANIMATION_DURATION_DEFAULT);
				showPOILayer(items,true);
			}
		}


		super.onActivityResult(requestCode, resultCode, data);
	}

	private void setTitle(){
		final TextView leftText = (TextView) findViewById(R.id.left_text);
		if(leftText != null)
			leftText.setText(mOsmv.getRenderer().NAME);

		final TextView rightText = (TextView) findViewById(R.id.right_text);
		if(rightText != null){
			rightText.setText(mStatusListener + " " + (1+mOsmv.getZoomLevel()));
		}
	}
	
	//joeng
	private void unSetPOIitems(){
		if (this.mMyPOIOverlay != null){
			this.mMyPOIOverlay.unSetFocusedItem();
		}
	}

	private class MainActivityCallbackHandler extends Handler{
		@Override
		public void handleMessage(final Message msg) {
			final int what = msg.what;
			switch(what){
				case R.id.user_moved_map:
					Log.d(DEBUGTAG, "user_moved_map");
					setAutoFollow(false);
					break;
				case R.id.user_double_tap:
					setTitle();
					break;
				//joeng POI
				case R.id.user_single_tap:
					unSetPOIitems();
					break;
				case R.id.user_long_press: 
					showEditPOIDialog(MainView.this, msg.arg1 , msg.arg2);
					break;					
				case R.id.max_zoom_limit:
					setMaxMinZoom(false,true);
					break;
				case R.id.min_zoom_limit:
					setMaxMinZoom(true,false);
					break;
				case R.id.normal_zoom:
					setMaxMinZoom(true,true);
					break;					
			}		
		}
	}

	@Override
	public boolean onSearchRequested() {
        startSearch("", false, null, false);
		return true;
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

        final String queryAction = intent.getAction();
        if (Intent.ACTION_SEARCH.equals(queryAction)) {
            doSearchQuery(intent);
        }
	}
	
	private void doSearchQuery(Intent queryIntent) {
		mSearchResultOverlay.Clear();
		this.mOsmv.invalidate();

		final String queryString = queryIntent.getStringExtra(SearchManager.QUERY);

        // Record the query string in the recent queries suggestions provider.
        SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this, SearchSuggestionsProvider.AUTHORITY, SearchSuggestionsProvider.MODE);
        suggestions.saveRecentQuery(queryString, null);

		InputStream in = null;
		OutputStream out = null;

		try {
			URL url = new URL(
					"http://ajax.googleapis.com/ajax/services/search/local?v=1.0&sll="
							+ this.mOsmv.getMapCenter().toDoubleString()
							+ "&q=" + URLEncoder.encode(queryString, "UTF-8")
							+ "");
			Ut.dd(url.toString());
			in = new BufferedInputStream(url.openStream(), StreamUtils.IO_BUFFER_SIZE);

			final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
			out = new BufferedOutputStream(dataStream, StreamUtils.IO_BUFFER_SIZE);
			StreamUtils.copy(in, out);
			out.flush();

			String str = dataStream.toString();
			JSONObject json = new JSONObject(str);
			//Ut.dd(json.toString(4)); //
			JSONArray results = (JSONArray) ((JSONObject) json.get("responseData")).get("results");
			//Ut.dd("results.length="+results.length());
			if(results.length() == 0){
				Toast.makeText(this, R.string.no_items, Toast.LENGTH_SHORT).show();
				return;
			}
			JSONObject res = results.getJSONObject(0);
			//Ut.dd(res.toString(4));
			//Toast.makeText(this, res.getString("titleNoFormatting"), Toast.LENGTH_LONG).show();
			final String address = res.getString("addressLines").replace("\"", "").replace("[", "").replace("]", "").replace(",", ", ").replace("  ", " ");
			//Toast.makeText(this, address, Toast.LENGTH_LONG).show();
			//Toast.makeText(this, ((JSONObject) json.get("addressLines")).toString(), Toast.LENGTH_LONG).show();

			setAutoFollow(false, true);
			this.mSearchResultOverlay.setLocation(new GeoPoint((int)(res.getDouble("lat")* 1E6), (int)(res.getDouble("lng")* 1E6)), address);
			this.mOsmv.setZoomLevel((int) (2 * res.getInt("accuracy")));
			this.mOsmv.getController().animateTo(new GeoPoint((int)(res.getDouble("lat")* 1E6), (int)(res.getDouble("lng")* 1E6)), OpenStreetMapViewController.AnimationType.MIDDLEPEAKSPEED, OpenStreetMapViewController.ANIMATION_SMOOTHNESS_HIGH, OpenStreetMapViewController.ANIMATION_DURATION_DEFAULT);

			setTitle();

		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, R.string.no_inet_conn, Toast.LENGTH_LONG).show();
		} finally {
			StreamUtils.closeStream(in);
			StreamUtils.closeStream(out);
		}
	}
	
	private void setAutoFollow(boolean autoFollow, final boolean supressToast) {
		if (mAutoFollow != autoFollow) {
			mAutoFollow = autoFollow;

			if (autoFollow) {
				ivAutoFollow.setVisibility(ImageView.INVISIBLE);
				if(!supressToast)
					Toast.makeText(this, R.string.auto_follow_enabled, Toast.LENGTH_SHORT).show();
			} else {
				ivAutoFollow.setVisibility(ImageView.VISIBLE);
				if(!supressToast)
					Toast.makeText(this, R.string.auto_follow_disabled, Toast.LENGTH_SHORT).show();
			}
		}
	}

	//joeng POI
	/**
	 * Return Value Description.
	 * 0: no error
	 * 1: if new POI already exist when adding new POI or updating an exist POI
	 */
	private Integer setPOI(String aID, String aName, String aDescription,int Latitude, int Longitude, 
			String Category, String City, String EditMode, String Hide, boolean SkipDuplicateCheck)
	{
		aName = aName.replaceAll("'", "''");
		aDescription = aDescription.replaceAll("'", "''");
		String newPlaceID = "";
		//Toast.makeText(this, "X:"+Integer.toString(Latitude)+"|Y:"+Integer.toString(Longitude), 4000);
		if (EditMode == "Add"){
			final Cursor c = this.mPOI.rawQuery("Select * from PlacesInfo where name = '" + aName + 
					"' and category = '" + Category	+ "' and city = '" + City + "'", null);
			if (c.getCount()>0){
				c.close();
				return 1; //new record already exist
			}
			c.close();
			final ContentValues cv = new ContentValues();
			cv.put("name", aName);
			cv.put("description", aDescription);
			//cv.put("latitude", Latitude);
			//cv.put("longitude", Longitude);
			cv.put("category", Category);
			cv.put("show", true);
			cv.put("city", City);
			this.mPOI.insert("PlacesInfo", null, cv);
			
			final Cursor c1 = this.mPOI.rawQuery("select last_insert_rowid()", null);
			if (c1.moveToFirst())
				newPlaceID = c1.getString(0);
			c1.close();
			this.mPOI.execSQL("Insert into PlacesGeoPoint values('" + newPlaceID + "','" + Latitude + "','" + Longitude + "')");
			showPOILayer(items,newPlaceID, aName,aDescription,Latitude,Longitude,true,Category,City);
		}else if (EditMode == "Update"){
			if (!SkipDuplicateCheck){
				final Cursor c = this.mPOI.rawQuery("Select * from PlacesInfo where name = '" + aName + 
						"' and category = '" + Category	+ "' and city = '" + City + "'", null);
				if (c.getCount()>0){
					c.close();
					return 1; // there is already a POI with same key exist
				}
				c.close();
			}
			this.mPOI.execSQL("Update PlacesInfo set name = '" + aName + "', category = '" + Category	+ "', city = '" + City + "', " +
					"description = '" + aDescription + "', show = " + Hide + " where PlaceID = "+ aID +";");
			showPOILayer(items,true);
		}else if (EditMode == "Delete"){
			this.mPOI.delete("PlacesInfo", "name = '" + aName + "' and category = '" + Category	+ "' " +
					"and city = '" + City + "'" , null);
			this.mPOI.delete("PlacesGeoPoint", "PlaceID = '" + aID + "'" , null);
			this.unSetPOIitems();
			showPOILayer(items,true);
		}
		return 0;
	}
	//joeng POI
	private void showEditPOIDialog(final Context context, final int Latitude, final int Longitude) {
		showEditPOIDialog(context,"","","","","",Latitude,Longitude,true);
	}
	private void showEditPOIDialog(final Context context, final String ID,  final String Name, String Description, String Category, 
			String City,final int Latitude, final int Longitude, boolean NewPOI) {
		//View v = View.inflate(context, NewPOI ? R.layout.addpoi : null, null);
		View v = View.inflate(context, R.layout.editpoi , null);
		final AlertDialog dialog = new AlertDialog.Builder(context).create();
		dialog.setView(v);
		
		//set title
		dialog.setTitle(NewPOI ? R.string.edit_poi_title_new : R.string.edit_poi_title_update);

		//set name & description
		final EditText nameValue = (EditText) v.findViewById(R.id.nameValue);
		if (!NewPOI) {nameValue.setText(Name);}
		final EditText descriptionValue = (EditText) v.findViewById(R.id.descriptionValue);
		if (!NewPOI) {descriptionValue.setText(Description);}
	
		// set city
		final EditText cityValue = (EditText) v.findViewById(R.id.cityValue);
		cityValue.setVisibility(View.GONE);
		
		//set poi category
		final Spinner poiCategory = (Spinner) v.findViewById(R.id.poicategory);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.poi_category,
                android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        poiCategory.setAdapter(adapter);
        if (!NewPOI) {
        	poiCategory.setSelection(adapter.getPosition(Category));
        	poiCategory.setFocusableInTouchMode(true);
        	poiCategory.requestFocus();
        }
        
		final TextView validationError = (TextView) v.findViewById(R.id.validationError); 
		
		//set delete check box
		final CheckBox ckbDelete = (CheckBox) v.findViewById(R.id.CKBDelete);
		ckbDelete.setChecked(false);
		ckbDelete.setVisibility(NewPOI? View.GONE: View.VISIBLE);
		final CheckBox ckbHide = (CheckBox) v.findViewById(R.id.CKBHide);
		ckbHide.setChecked(false);
		ckbHide.setVisibility(NewPOI? View.GONE: View.VISIBLE);
		
		
		final Button cancelBtn = (Button) v.findViewById(R.id.cancelBtn);
		cancelBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		
		final Button addBtn = (Button) v.findViewById(R.id.addBtn);
		addBtn.setText(NewPOI ? "Add" : "Update");
		
		addBtn.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				String name = nameValue.getText().toString();
				boolean SkipDuplicateCheck = name.equalsIgnoreCase(Name);
				String description = descriptionValue.getText().toString();
				if(name.trim().length() ==0){
					validationError.setText(R.string.EMPTY_NAME_ERROR);
				}else {
					if (addBtn.getText()== "Add"){ //add new POI
						if (setPOI("",name,description,Latitude,Longitude,(String)poiCategory.getSelectedItem(),"Default", "Add","0",false) == 1){
							validationError.setText("Duplicate POI, please change the Name.");
							//Toast.makeText(MainView.this, "Duplicate POI found, please change the Name.", Toast.LENGTH_SHORT).show();							
						}
						else
							dialog.dismiss();
					}
					else if (addBtn.getText()== "Update"){ //update an existed POI
						if (ckbDelete.isChecked()){
							setPOI(ID,name,description,Latitude,Longitude,(String)poiCategory.getSelectedItem(),"Default", "Delete","0",true);
							dialog.dismiss();
						}else {
							if (setPOI(ID,name,description,Latitude,Longitude,(String)poiCategory.getSelectedItem(),"Default", "Update", 
									ckbHide.isChecked()? "0" : "1", SkipDuplicateCheck) == 1 ){
								validationError.setText("Duplicate POI, please change the Name.");
								//Toast.makeText(MainView.this, "Duplicate POI found, please change the Name.", Toast.LENGTH_SHORT).show();
							}
							else
								dialog.dismiss();
						}
					}
				}
			}
		});
		
		final Button gotoBtn = (Button) v.findViewById(R.id.gotoBtn);
		gotoBtn.setVisibility(View.GONE);

		dialog.setCancelable(true);
		dialog.show();
	}


}
